<template>
  <div ref="chartRef" :style="{ width: width, height: height }" />
</template>

<script lang="ts">
import { defineComponent, onMounted, onBeforeUnmount, ref, watch } from "vue";
import * as echarts from "echarts";

export default defineComponent({
  name: "ECharts",
  props: {
    options: {
      type: Object as () => echarts.EChartsOption,
      required: true,
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
  },
  setup(props, { emit }) {
    const chartRef = ref<HTMLDivElement | null>(null);
    let chartInstance: echarts.ECharts | null = null;

    const initChart = () => {
      if (chartRef.value) {
        chartInstance = echarts.init(chartRef.value);
        chartInstance.setOption(props.options);
        chartInstance.on("click", (params: any) => {
          emit("chart-click", params);
        });
      }
    };

    const resizeChart = () => {
      if (chartInstance) {
        chartInstance.resize();
      }
    };

    onMounted(() => {
      initChart();
      window.addEventListener("resize", resizeChart);
    });

    onBeforeUnmount(() => {
      if (chartInstance) {
        chartInstance.dispose();
      }
      window.removeEventListener("resize", resizeChart);
    });

    watch(
      () => props.options,
      (newOptions) => {
        if (chartInstance) {
          chartInstance.setOption(newOptions);
        }
      },
      { deep: true }
    );

    return {
      chartRef,
    };
  },
});
</script>

<style scoped>
/* 你可以在这里添加一些样式 */
</style>
